//
//  GKContentController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2019/9/10.
//  Copyright © 2019 wangws1990. All rights reserved.
//

import UIKit
import AVFoundation
class GKNovelContentController: BaseViewController,
UIPageViewControllerDelegate,
UIPageViewControllerDataSource,
DZMCoverControllerDelegate,
GKNovelSetDelegate,
GKNovelDirectoryDelegate {
    
    
    class func vcWitBookId(bookModel : GKBookModel) -> GKNovelContentController{
        let vc : GKNovelContentController = GKNovelContentController.init();
        vc.bookModel = bookModel;
        return vc;
    }
    var pageCtrl :UIPageViewController!
    var covelCtrl :DZMCoverController!
    var bookModel :GKBookModel!
    var source :GKNovelSource!;
    var chapterInfo:GKNovelChapterInfo!;
    var content :GKNovelContent!;
    var chapter :NSInteger = 0;
    var pageIndex :NSInteger = 0;
    var _turnPage:Bool!
    var volice:Float = 0;
    var turnPage:Bool{
        set{
            _turnPage = newValue;
        }get{
            let set :GKNovelSet = GKNovelSetManager.manager.model;
            return set.browse == GKNovelBrowse.pageCurl;
        }
    }
    lazy var topView: GKNovelTopView = {
        let topView :GKNovelTopView = GKNovelTopView.instanceView();
        topView.isHidden = true;
        topView.backBtn.addTarget(self, action:#selector(goBackAction), for: .touchUpInside);
        return topView
    }()
    lazy var tabView: GKNovelTabView = {
        let tabView :GKNovelTabView = GKNovelTabView.instanceView();
        tabView.dayBtn.addTarget(self, action: #selector(dayAction(sender:)), for: .touchUpInside);
        tabView.setBtn.addTarget(self, action: #selector(setAction), for: .touchUpInside);
        tabView.muluBtn.addTarget(self, action:#selector(muluAction), for: .touchUpInside);
        tabView.nextBtn.addTarget(self, action: #selector(nextAction), for: .touchUpInside);
        tabView.lastBtn.addTarget(self, action: #selector(lastAction), for: .touchUpInside);
        tabView.slider.addTarget(self, action: #selector(sliderAction(sender:)), for: .touchUpInside)
        tabView.isHidden = true;
        return tabView
    }()
    lazy var setView : GKNovelSetView = {
        let setView : GKNovelSetView = GKNovelSetView.instanceView();
        setView.delegate = self;
        setView.isHidden = true;
        return setView
    }()
    lazy var tapView : UIView = {
        let tap:UIView = UIView.init();
        tap.isHidden = true;
        tap.backgroundColor = UIColor.clear;
        return tap;
    }()
    lazy var directoryView: GKNovelDirectoryView = {
        let view : GKNovelDirectoryView = GKNovelDirectoryView.instanceView();
        view.delegate = self;
        view.isHidden = true;
        return view;
    }()
    deinit {
        NotificationCenter.default.removeObserver(self);
        UIApplication.sharedExtension()?.endReceivingRemoteControlEvents();
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNeedsStatusBarAppearanceUpdate();
        loadUI();
        loadData();
        loadNotification();
    }

    func loadUI(){
        self.fd_prefersNavigationBarHidden = true;
        self.view.addSubview(self.topView);
        self.topView.snp_makeConstraints { (make) in
            make.top.equalToSuperview().offset(-NAVI_BAR_HIGHT)
            make.left.right.equalToSuperview();
            make.height.equalTo(NAVI_BAR_HIGHT)
        }
        self.view.addSubview(self.setView);
        self.view.addSubview(self.tabView);
        self.tabView.snp_makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(95+TAB_BAR_ADDING)
            make.left.right.equalToSuperview();
            make.height.equalTo(95+TAB_BAR_ADDING);
        }
        self.view.addSubview(self.tapView);
        self.setView.snp_makeConstraints { (make) in
            make.left.right.equalToSuperview();
            make.height.equalTo(200);
            make.top.equalTo(self.tabView.snp_top);
        }
        self.view.addSubview(self.directoryView);
        self.directoryView.snp_makeConstraints { (make) in
            make.top.bottom.equalToSuperview();
            make.width.equalTo(SCREEN_WIDTH);
            make.left.equalToSuperview().offset(-SCREEN_WIDTH);
        }
        let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapAction(sender:)));
        tap.delegate = self;
        self.view.addGestureRecognizer(tap);

        let tapMy:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapMyAction));
        self.tapView.addGestureRecognizer(tapMy);
        
        if self.turnPage {
            self.loadPageCtrlUI()
        }else{
            self.loadCovelCtrlUI();
        }
    }
    func loadNotification(){
        do {
            try AVAudioSession.sharedInstance().setActive(true);
        } catch {
            
        }
        NotificationCenter.default.addObserver(self, selector: #selector(notificationAction(notification:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil);
        UIApplication.sharedExtension()?.beginReceivingRemoteControlEvents();
        
    }
    @objc func notificationAction(notification : NSNotification){
        print(notification.name);
        if notification.name.rawValue != "AVSystemController_SystemVolumeDidChangeNotification"  {
            return;
        }
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary;
        let reason : String = userInfo.object(forKey:"AVSystemController_AudioVolumeChangeReasonNotificationParameter") as! String
        if reason != "ExplicitVolumeChange" {
            return;
        }
        let volume : Float = userInfo.object(forKey: "AVSystemController_AudioVolumeNotificationParameter") as! Float;
        if self.volice == 0 {
            self.volice = volume;
        }
        DispatchQueue.main.async {
        if (self.volice > volume || (self.volice == 0 && volume == 0)) {
                       self.leftAction();
                   }else{
                       self.rightAction();
                   }
        }
        print(reason);
    }
    @objc func tapAction(sender:UITapGestureRecognizer){
        if self.topView.isHidden == false {
            return;
        }
        let point : CGPoint = sender.location(in:self.view);
        if point.x > SCREEN_WIDTH/3.0 && point.x < SCREEN_WIDTH/3.0*2 {
            self.topView.isHidden ? self.showTopView() : self.hiddenTopView();
        }
    }
    @objc func goBackAction() {
        self.goBack();
        DispatchQueue.global().async {
            self.inseDataQueue();
        };
        BaseNetCache.removeMemory();
    }
    @objc func tapMyAction(){
        if self.setView.isHidden == false {
            self.setAction();
        }
        self.hiddenTopView();
    }
    @objc func dayAction(sender:UIButton){
        sender.isSelected = !sender.isSelected;
        GKNovelSetManager.setNight(night: sender.isSelected);
        self.reloadUI();
    }
    @objc func setAction(){
        if self.setView.isHidden {
            self.setView.isHidden = false;
            self.setView.snp_remakeConstraints { (make) in
                make.left.right.equalToSuperview();
                make.height.equalTo(200);
                make.top.equalTo(self.tabView.snp_top).offset(-200);
            }
            UIView.animate(withDuration: 0.35) {
                self.view.layoutIfNeeded();
            }
            self.tapView.snp_remakeConstraints { (make) in
                make.left.right.equalToSuperview();
                make.top.equalTo(self.topView.snp_bottom);
                make.bottom.equalTo(self.setView.snp_top);
                
            }
        }else{
            self.setView.snp_remakeConstraints { (make) in
                make.left.right.equalToSuperview();
                make.height.equalTo(200);
                make.top.equalTo(self.view.snp_bottom).offset(0);
            }
            UIView.animate(withDuration: 0.35, animations: {
                self.view.layoutIfNeeded()
            }) { (finish) in
                self.setView.isHidden = true;
            }
        }
    }
    @objc func muluAction(){
        if self.topView.isHidden == false {
            self.tapMyAction();
        }
        if self.directoryView.isHidden {
            self.directoryView.isHidden = false;
            self.directoryView.snp_remakeConstraints { (make) in
                make.top.bottom.equalToSuperview();
                make.width.equalTo(SCREEN_WIDTH);
                make.left.equalToSuperview();
            }
            UIView.animate(withDuration: 0.3, animations: {
                self.view.layoutIfNeeded();
            }) { (finifsh) in
                
                self.setNeedsStatusBarAppearanceUpdate();
            }
        }else{
            self.directoryView.snp_remakeConstraints { (make) in
                make.top.bottom.equalToSuperview();
                make.width.equalTo(SCREEN_WIDTH);
                make.left.equalToSuperview().offset(-SCREEN_WIDTH);
            }
            UIView.animate(withDuration: 0.3, animations: {
                self.view.layoutIfNeeded();
            }) { (finifsh) in
                self.directoryView.isHidden = true;
                self.setNeedsStatusBarAppearanceUpdate();
            }
        }
    }
    @objc func sliderAction(sender:UISlider){
        self.pageIndex = Int(sender.value);
        self.reloadUI();
    }
    @objc func nextAction(){
        let listData = self.chapterInfo.chapters;
        if self.chapter + 1 >= listData!.count {
            MBProgressHUD.showMessage("已经是最后一章");
            return;
        }
        self.chapter = self.chapter + 1;
        self.pageIndex = 0;
        self.bookContent(chapter: self.chapter);
        
    }
    @objc func lastAction(){
        if self.chapter == 0 {
            MBProgressHUD.showMessage("已经是第一章");
            return;
        }
        self.chapter = self.chapter - 1;
        self.pageIndex = 0;
        self.bookContent(chapter: self.chapter);
    }
    func showTopView(){
        self.topView.isHidden = false;
        self.tabView.isHidden = self.topView.isHidden;
        self.tapView.isHidden = self.topView.isHidden;
        self.topView.snp_remakeConstraints { (make) in
            make.top.equalToSuperview().offset(0)
            make.left.right.equalToSuperview();
            make.height.equalTo(NAVI_BAR_HIGHT)
        }
        self.tabView.snp_remakeConstraints { (make) in
            make.bottom.equalToSuperview().offset(0)
            make.left.right.equalToSuperview();
            make.height.equalTo(95+TAB_BAR_ADDING);
        }
        self.tapView.snp_remakeConstraints { (make) in
            make.left.right.equalToSuperview();
            make.top.equalTo(self.topView.snp_bottom);
            make.bottom.equalTo(self.tabView.snp_top);
            
        }
        UIView.animate(withDuration: 0.35, animations: {
            self.view.layoutIfNeeded();
        }) { (finish) in
            self.setNeedsStatusBarAppearanceUpdate();
        }
    }
    func hiddenTopView(){
        self.topView.snp_remakeConstraints { (make) in
            make.top.equalToSuperview().offset(-NAVI_BAR_HIGHT)
            make.left.right.equalToSuperview();
            make.height.equalTo(NAVI_BAR_HIGHT)
        }
        self.tabView.snp_remakeConstraints { (make) in
            make.bottom.equalToSuperview().offset(95+TAB_BAR_ADDING)
            make.left.right.equalToSuperview();
            make.height.equalTo(95+TAB_BAR_ADDING);
        }
        UIView.animate(withDuration: 0.35, animations: {
            self.view.layoutIfNeeded();
        }) { (finish) in
            
            self.topView.isHidden = true;
            self.tabView.isHidden = self.topView.isHidden;
            self.tapView.isHidden = self.topView.isHidden;
            self.setNeedsStatusBarAppearanceUpdate();
        }
    }
    func loadData(){
        GKBrowseDataQueue.getBookModel(bookId: self.bookModel.bookId) { (model) in
            if model.bookId == nil || model.chapterInfo == nil{
                self.bookSummary();
            }else{
                self.chapter = model.chapter;
                self.pageIndex = model.pageIndex;
                self.source = model.source;
                self.chapterInfo = model.chapterInfo;
                self.bookContent(chapter: self.chapter)
            }
        }
        let set :GKNovelSet = GKNovelSetManager.manager.model;
        self.tabView.dayBtn.isSelected = set.night;
        
        self.topView.titleLab.text = self.bookModel.title ?? "";
        
    }
    func bookSummary(){
        GKNovelNetManager.bookSummary(bookId: self.bookModel.bookId, sucesss: { (source) in
            self.source = source;
            self.bookChapters()
        }) { (error) in
            
        };
    }
    func bookChapters(){
        GKNovelNetManager.bookChapters(bookId: self.source._id, sucesss: { (object) in
            self.chapterInfo = object;
            self.bookContent(chapter: 0)
        }) { (error) in
            
        };
    }
    func bookContent(chapter:NSInteger){
        let info :GKNovelChapter = self.chapterInfo.chapters[chapter];
        
        GKNovelNetManager.bookContentModel(bookId:self.bookModel.bookId, model: info, sucesss: { (content) in
            self.content = content;
            self.reloadUI()
        }) { (error) in
            
        }
    }
    func removePageCtrlUI(){
        if (self.pageCtrl != nil) {
            self.pageCtrl.view.removeFromSuperview();
            self.pageCtrl.removeFromParentViewController();
            self.pageCtrl.dataSource = nil;
            self.pageCtrl.delegate = self;
            self.pageCtrl = nil;
        }
    }
    func loadPageCtrlUI(){
        self.removePageCtrlUI();
        self.removewCovelCtrlUI()
        let vc :UIViewController = GKNovelItemController.init();
        self.pageCtrl = UIPageViewController.init(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
        self.pageCtrl.dataSource = self;
        self.pageCtrl.delegate = self;
        self.pageCtrl.setViewControllers([vc], direction: .forward, animated: false, completion: nil);
        self.addChildViewController(self.pageCtrl);
        self.view.addSubview(self.pageCtrl.view);
        self.view.sendSubview(toBack: self.pageCtrl.view);
        self.pageCtrl.didMove(toParentViewController: self);
        self.pageCtrl.view.snp_makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
    }
    func removewCovelCtrlUI(){
        if (self.covelCtrl != nil) {
            self.covelCtrl.view.removeFromSuperview();
            self.covelCtrl.removeFromParentViewController();
            self.covelCtrl.delegate = self;
            self.covelCtrl = nil;
        }
    }
    func loadCovelCtrlUI(){
        let model :GKNovelSet = GKNovelSetManager.manager.model;
        self.removePageCtrlUI();
        self.removewCovelCtrlUI()
        let vc :UIViewController = GKNovelItemController.init();
        self.covelCtrl = DZMCoverController.init()
        self.covelCtrl.setController(vc);
        self.covelCtrl.delegate = self;
        self.covelCtrl.openAnimate = (model.browse == .defaults);
        self.addChildViewController(self.covelCtrl);
        self.view.addSubview(self.covelCtrl.view);
        self.view.sendSubview(toBack: self.covelCtrl.view);
        self.covelCtrl.didMove(toParentViewController: self);
        self.covelCtrl.view.snp_makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
    }
    func reloadUI(){
        self.content.setContentPage();
        self.turnPage ? self.reloadPageCtrlUI():self.reloadCovelCtrlUI()
        self.tabView.slider.maximumValue = Float(self.content.pageCount-1);
        self.tabView.slider.minimumValue = 0;
        self.directoryView.setDatas(listData: self.chapterInfo.chapters);
        self.directoryView.chapter = self.chapterInfo.chapters[self.chapter];
        
    }
    func reloadPageCtrlUI(){
        let vc:GKNovelItemController = self.readCtrl();
        self.pageCtrl.setViewControllers([vc], direction: .forward, animated: false, completion: nil);
    }
    func reloadCovelCtrlUI(){
        let vc:GKNovelItemController = self.readCtrl();
        self.covelCtrl.setController(vc);
    }
    func changeFont(setView: GKNovelSetView) {
        self.reloadUI();
    }
    
    func changeRead(setView: GKNovelSetView) {
        if self.turnPage {
            self.loadPageCtrlUI()
        }else{
            self.loadCovelCtrlUI();
        }
        self.reloadUI()
    }
    
    func changeSkin(setView: GKNovelSetView) {
        self.reloadUI();
    }
    func closeDirectoryView(view: GKNovelDirectoryView) {
        self.muluAction();
    }
    
    func selectChapter(view: GKNovelDirectoryView, chapter: NSInteger) {
        self.chapter = chapter;
        self.pageIndex = 0;
        self.bookContent(chapter:self.chapter);
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool{
        print(NSStringFromClass(touch.view!.classForCoder))
        let str:String = NSStringFromClass(touch.view!.classForCoder)
        let view : UIView = touch.view!;
        if str.elementsEqual("UITableViewCellContentView") {
            return false;
        }
        if view.tag == 10086 {
            return false;
        }
        return true;
    }
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        let vc:GKNovelItemController = self.pageCtrl.viewControllers?.first as! GKNovelItemController
        self.currentCtrl(ctrl:vc);
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        return self.beforeCtrl()
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        return self.afterCtrl();
    }
    internal func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation {
        let vc = pageViewController.viewControllers?.first
        if (vc != nil) {
            self.pageCtrl.setViewControllers([vc!], direction: .forward, animated: true, completion: nil);
            return .min;
        }
        return.none;
    }
    func coverController(_ coverController: DZMCoverController, currentController: UIViewController?, finish isFinish: Bool) {
        self.currentCtrl(ctrl:currentController as! GKNovelItemController);
    }
    func coverController(_ coverController: DZMCoverController, getAboveControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        return self.beforeCtrl()
    }
    func coverController(_ coverController: DZMCoverController, getBelowControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        return self.afterCtrl();
    }
    func leftAction(){
        let vc:UIViewController = self.beforeCtrl();
        if self.turnPage {
            self.pageCtrl.setViewControllers([vc], direction: .forward, animated: false, completion: nil);
        }else{
            self.covelCtrl.setController(vc);
        }
    }
    func rightAction(){
        let vc:UIViewController = self.afterCtrl();
        if self.turnPage {
            self.pageCtrl.setViewControllers([vc], direction: .forward, animated: false, completion: nil);
        }else{
            self.covelCtrl.setController(vc);
        }
    }

    func currentCtrl(ctrl:GKNovelItemController) {
        if self.pageIndex != ctrl.pageIndex {
            self.pageIndex = ctrl.pageIndex;
        }
        if self.chapter != ctrl.chapter {
            self.chapter = ctrl.chapter;
            self.getNovelContent(chapter: self.chapter);
        }
    }
    func beforeCtrl() -> GKNovelItemController{
        let vc :GKNovelItemController = self.turnPage ? (self.pageCtrl.viewControllers?.first as? GKNovelItemController)! : self.covelCtrl!.currentController as! GKNovelItemController;
        if self.pageIndex <= 0 && self.chapter <= 0 {
            MBProgressHUD.showMessage("当前第一章，第一页")
            self.chapter = 0;
            self.pageIndex = 0;
            //return GKNovelItemController.init();
        }else if(self.pageIndex <= 0){
            if vc.chapter == self.chapter{
                self.chapter  = self.chapter - 1;
                self.getNovelContent(chapter: self.chapter);
                self.pageIndex = self.content.pageCount - 1;
            }
        }else{
            if vc.pageIndex == self.pageIndex{
                self.pageIndex = self.pageIndex - 1;
            }
        }
        return self.readCtrl()
    }
    func afterCtrl() -> GKNovelItemController{
         let vc :GKNovelItemController = self.turnPage ? (self.pageCtrl.viewControllers?.first as? GKNovelItemController)! : self.covelCtrl!.currentController as! GKNovelItemController;
        let chapters :NSArray = self.chapterInfo!.chapters! as NSArray;
        if self.pageIndex >= self.content.pageCount - 1 && self.chapter >= chapters.count {
            MBProgressHUD.showMessage("当前最后一章，最后一页")
            return GKNovelItemController.init();
        }else if(self.pageIndex >= self.content.pageCount - 1){
            if vc.chapter == self.chapter{
                self.chapter = self.chapter + 1;
                self.getNovelContent(chapter: self.chapter);
                self.pageIndex = 0;
            }
        }else{
            if(vc.pageIndex == self.pageIndex){
                self.pageIndex = self.pageIndex + 1;
            }
        }
        return self.readCtrl();
    }
    func readCtrl() -> GKNovelItemController{
        let vc:GKNovelItemController = GKNovelItemController();
        self.getBeforeData();
        self.getAfterData();
        vc.setModel(model:self.content, chapter: self.chapter, pageIndex: self.pageIndex);
        self.tabView.slider.value = Float(self.pageIndex)
        return vc;
    }
    func getBeforeData(){
        let chapterData :NSArray = self.chapterInfo!.chapters! as NSArray;
        let chapter:NSInteger = self.chapter - 1;
        if chapter >= 0 && chapterData.count > chapter {
            let info:GKNovelChapter = chapterData[chapter] as! GKNovelChapter;
            GKNovelNetManager.bookContentModel(bookId:self.bookModel.bookId, model: info, sucesss: { (content) in
                BaseNetCache.setMemoryObject(content, forkey:info.chapterId);
            }) { (error) in
                
            }
        }
    }
    func getAfterData(){
        let chapterData :NSArray = self.chapterInfo!.chapters! as NSArray;
        let chapter:NSInteger = self.chapter + 1;
        if self.content.pageCount > self.pageIndex && chapterData.count > chapter {
            let info:GKNovelChapter = chapterData[chapter] as! GKNovelChapter;
            GKNovelNetManager.bookContentModel(bookId:self.bookModel.bookId, model: info, sucesss: { (content) in
                BaseNetCache.setMemoryObject(content, forkey:info.chapterId);
            }) { (error) in
                
            }
        }
    }
    func getNovelContent(chapter:NSInteger){
        let chapters:[GKNovelChapter] = self.chapterInfo.chapters;
        let info:GKNovelChapter = chapters[chapter];
        self.content = info.getContent();
        if info.chapterId == nil {
            let content :GKNovelContent = GKNovelContent.init();
            content.content = "更多精彩内容请耐心等待...";
            self.content = content;
        }
        self.content.setContentPage();
    }
    func inseDataQueue(){
        let model:GKBrowseModel = GKBrowseModel.init();
        model.bookId = self.bookModel.bookId;
        model.chapter = self.chapter;
        model.pageIndex = self.pageIndex;
        let time : TimeInterval = Date.init().timeIntervalSince1970;
        model.updateTime = String(time);
        model.chapterInfo = self.chapterInfo;
        model.source = self.source;
        model.bookModel = self.bookModel;
        GKBrowseDataQueue.insertBookModel(browse: model) { (success) in
            
        }
    }
    override var prefersStatusBarHidden: Bool{
        return (self.topView.isHidden == false || self.directoryView.isHidden == false) ? false : true;
    }
}
